 /*!
 * @author @huntbao
 * @upload
 */
;(function($){
    App.uploadHelper = {
        init: function(appView){
            var self = this,
            globalMiniProgressBar,
            initGlobalMiniProgressBar = function(){
                if(!globalMiniProgressBar){
                    globalMiniProgressBar = $('<div class="mini-progressall"><div class="progress-tip">' + App.i18n.get('readyToUpload') + '</div><div class="progress"><div class="bar"></div></div></div>')
                    .hide().appendTo(document.body).click(function(){
                        $('#mod-plupload').modal('show');
                        $(this).hide();
                    });
                }
            },
            isUploading = false;
            $('#mod-plupload').modal({
                keyboard: true,
                show: false,
                backdrop: "static"
            }).pluploadQueue({
                 runtimes : 'html5, flash',
                 url : '/document/file/upload.json',
                 max_file_size : App.quota.total - App.quota.used,
                 unique_names : true,
                 flash_swf_url : '/document/js/libs/jquery/plupload/plupload.flash.swf',
                 multipart: true,
                 init: {
                    FilesAdded: function(up, files){
                        if(files.length > 100){
                            var nativeFiles = up.getNativeFiles();
                            up.splice();
                            var allFiles = [];
                            for(var f in nativeFiles){
                                allFiles.push(nativeFiles[f]);
                            }
                            for(var i = 0; i < allFiles.length; i += 100){
                                up.addFiles(allFiles.slice(i, i + 100));
                            }
                            return;
                        }
                        initGlobalMiniProgressBar();
                        if($.browser.safari){
                            //safari 5.1.7's File API not support slice method, so can not upload part of the file - 2012.11.28
                            _.each(files, function(file){
                                file.uploadedBytes = 0;
                                file.parentId = appView.getParentId();
                            });
                            up.start();
                        }else{
                            var names = [],
                            sizes = [],
                            filesMap = {};
                            _.each(files, function(file, idx){
                                names.push(file.name);
                                sizes.push(file.size);
                                filesMap[idx] = file;
                            });
                            var parentId = appView.getParentId();
                            $.getJSON('getUploadedBytes.json', {
                                parentId: parentId,
                                name: names.join('"'),
                                size: sizes.join(',')
                            }, function(data){
                                data = data.result;
                                _.each(data, function(value, key){
                                    filesMap[key].uploadedBytes = value;
                                    filesMap[key].parentId = parentId;
                                });
                                up.start();
                            });
                        }
                    },
                    BeforeUpload: function(up, file){
                        if(typeof file.uploadedBytes === 'undefined'){
                            up.stop();
                        }else{
                            up.settings.multipart_params = {
                                parentId: file.parentId,
                                fullName: file.fullPath || file.name,
                                size: file.size,
                                position: file.uploadedBytes || 0
                            }
                            up.settings.uploaded_bytes = file.uploadedBytes || 0;
                        }
                    },
                    UploadProgress: function(up, file){
                        var percent = up.total.percent;
                        globalMiniProgressBar.find('.bar').css('width', percent + '%').end()
                        .find('.progress-tip').text(App.i18n.get('isUploadingFile') + percent + '%');
                    },
                    UploadFile: function(up, file){
                        isUploading = true;
                    },
                    FileUploaded: function(up, file, response){
                        try{
                            appView.addUploadFile(response);
                        }catch(e){
                            //todo
                        }
                    },
                    UploadComplete: function(up, file){
                        isUploading = false;
                        var progressTip = globalMiniProgressBar.find('.progress-tip');
                        if(up.total.failed !== 0){
                            progressTip.text(App.i18n.get('uploadCompletedWithSomeFailed', [up.total.failed])).next().addClass('progress-danger');
                        }else{
                            progressTip.text(App.i18n.get('uploadCompleted'));
                        }
                        if(globalMiniProgressBar.css('display') === 'block'){
                            $('#mod-plupload').pluploadQueue().reset();
                        }
                        setTimeout(function(){
                        	progressTip.text(App.i18n.get('readyToUpload'));
                            globalMiniProgressBar.hide().find('.bar').css('width', 0);
                        }, 2000);
                    },
                    FilesRemoved: function(up, files){
                        if(up.files.length === 0){
                            isUploading = false;
                        }
                    },
                    Error: function(up, file){
                        if(file.code === -500){
                            //upload initialize error, todo
                            return;
                        }
                        if(file.code === 4 || file.code === -200){
                            App.util.actionTip(App.i18n.get('someFileUploadFailed', [file.file.name]) + file.message);
                        }
                    }
                 }
            }).append($('<div>', {'class': 'close-btn plupload', title: App.i18n.get('close')}).click(function(){
                $(this).parent().modal('hide');
            })).on('hide', function(e){
                if(isUploading === false){
                    $('#mod-plupload').pluploadQueue().reset();
                }
                globalMiniProgressBar && globalMiniProgressBar[isUploading ? 'show' : 'hide']();
            }).on('shown', function(e){
                globalMiniProgressBar && globalMiniProgressBar.hide();
                var t = $(this);
                setTimeout(function(){
                    t.css('left', ($(window).width() - 800)/2)
                    .css('top', 150);
                }, 0);
            }).draggable({
                containment: 'document',
                handle: '.plupload_header'
            });
            
            if(!$.browser.mozilla){
                //firefox will abort all network request while escape is pressed.
                $('#mod-plupload').on('show', function(e){
                    var t = this;
                    $(document).on('keyup.bootstrap.uploadmodal', function(e){
                        if(e.which === 27){
                            $(t).modal('hide');
                            $(this).off('keyup.bootstrap.uploadmodal');
                        }
                    });
                });
            }
            //drag and drop upload
            if($.browser.chrome || $.browser.mozilla){
                var dragArea = $(document.body)
                .bind('drop',function(e){
                    dragArea.removeClass('dragupload-drag-over');
                    var files = e.originalEvent.dataTransfer.files,
                    items = e.originalEvent.dataTransfer.items;
                    if(items){
                        var allFiles = [];
                        if(items.length > 0){
                            initGlobalMiniProgressBar();
                            globalMiniProgressBar.show().find('.progress-tip').text(App.i18n.get('isReadingFile'));
                        }
                        for(var i = 0; i < items.length; i++) {
                            var entry = items[i].webkitGetAsEntry();
                            if(entry.isFile){
                                self.readFile(entry, function(file){
                                    allFiles.push(file);
                                });
                            }else if(entry.isDirectory){
                                initGlobalMiniProgressBar();
                                self.traverseDirectory(entry, function(file){
                                    allFiles.push(file);
                                });
                            }
                        }
                        var time = 1000;
                        var fileTimer = setTimeout(function(){
                            if(allFiles.length > 0){
                                appView.uploadFiles(allFiles);
                                allFiles = [];
                                time += 1000;
                                fileTimer = setTimeout(arguments.callee, time);
                            }else{
                                clearTimeout(fileTimer);
                            }
                        }, time);
                    }else{
                        if(files.length > 0){
                            initGlobalMiniProgressBar();
                            globalMiniProgressBar.show();
                            appView.uploadFiles(files);
                        }
                    }
                    return false;
                }).bind('dragenter dragover',function(e){
                    if(dragArea.find(e.target).length === 1){
                        dragArea.addClass('dragupload-drag-over');
                        return false;
                    }
                }).bind('dragleave', function(){
                    dragArea.removeClass('dragupload-drag-over');
                });
            }
        },
        
        traverseDirectory: function(entry, callback){
            var self = this;
            if(entry.isFile){
                self.readFile(entry, callback);
            }else if(entry.isDirectory){
                var dirReader = entry.createReader();
                dirReader.readEntries(function(entries){
                    var el = entries.length;
                    while(el--){
                        self.traverseDirectory(entries[el], callback);
                    }   
                });
            }           
        },
        
        readFile: function(fileEntry, callback){
            fileEntry.file(function(file){
                file.fullPath = fileEntry.fullPath;
                callback && callback(file);
            });
        },
        
        updateUploaderMaxFileSize: function(){
            $('#mod-plupload').pluploadQueue().settings.max_file_size = App.quota.total - App.quota.used;
        }
    }
})(jQuery);
